package org.jeecg.modules.lab.util;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.lab.aop.ForUpdate;



import java.lang.reflect.Field;
import java.util.Objects;

@Slf4j
public class BeanUtils {


 	/**
     * 获取变更内容
     * @param newBean 更改前的Bean
     * @param oldBean 更改后的Bean
     * @param <T>
     * @return
     */
    public static   <T> String getChangedFields(T newBean, T oldBean){
        Field[] fields = newBean.getClass().getDeclaredFields();
        StringBuilder builder = new StringBuilder();
        for(Field field : fields) {
            field.setAccessible(true);

            if (field.isAnnotationPresent(ForUpdate.class)) {

                Object newValue = null;
                Object oldValue = null;
                try {
                    newValue = field.get(newBean);
                    oldValue = field.get(oldBean);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if(!Objects.equals(newValue, oldValue)) {
                        builder.append(field.getAnnotation(ForUpdate.class).fieldName()); //获取字段名称
                            builder.append(": 【更改后：");
                            builder.append(newValue);
                            builder.append(", 更改前：");
                            builder.append(oldValue);
                            builder.append("】\n");
                        }
                    }

            }

        String updateStr = builder.toString();
        return updateStr;
    }
}

